<?php

function calculateAttack(&$attackers, &$defenders, $FleetTF, $DefTF)
{
	global $pricelist, $CombatCaps, $resource, $reslist;

	$TRES 	= array('attacker' => 0, 'defender' => 0);
	$ARES 	= $DRES = array('metal' => 0, 'crystal' => 0);
	$ROUND	= array();
	$RF		= array();
	
	foreach ($attackers as $fleetID => $attacker) 
	{
		foreach ($attacker['detail'] as $element => $amount) 
		{
			$ARES['metal'] 		+= $pricelist[$element]['cost'][901] * $amount;
			$ARES['crystal'] 	+= $pricelist[$element]['cost'][902] * $amount;
		}
	}

	foreach($CombatCaps as $e => $arr) {
		if(!isset($arr['sd'])) continue;
		
		foreach($arr['sd'] as $t => $sd) {
			if($sd == 0) continue;
			$RF[$t][$e] = $sd;
		}
	}
	
	$TRES['attacker']	= $ARES['metal'] + $ARES['crystal'];

	foreach ($defenders as $fleetID => $defender) 
	{
		foreach ($defender['def'] as $element => $amount)
		{
			if ($element < 300) {
				$DRES['metal'] 		+= $pricelist[$element]['cost'][901] * $amount;
				$DRES['crystal'] 	+= $pricelist[$element]['cost'][902] * $amount ;

				$TRES['defender'] 	+= $pricelist[$element]['cost'][901] * $amount;
				$TRES['defender'] 	+= $pricelist[$element]['cost'][902] * $amount;
			} else {
				if (!isset($STARTDEF[$element])) 
					$STARTDEF[$element] = 0;
				
				$STARTDEF[$element] += $amount;

				$TRES['defender']	+= $pricelist[$element]['cost'][901] * $amount;
				$TRES['defender']	+= $pricelist[$element]['cost'][902] * $amount;
			}
		}
	}
	
	for ($ROUNDC = 0; $ROUNDC <= MAX_ATTACK_ROUNDS; $ROUNDC++) 
	{
		$attackDamage  = array('total' => 0);
		$attackShield  = array('total' => 0);
		$attackAmount  = array('total' => 0);
		$defenseDamage = array('total' => 0);
		$defenseShield = array('total' => 0);
		$defenseAmount = array('total' => 0);
		$attArray = array();
		$defArray = array();

		foreach ($attackers as $fleetID => $attacker) {
			$attackDamage[$fleetID] = 0;
			$attackShield[$fleetID] = 0;
			$attackAmount[$fleetID] = 0;

			$attTech	= (1 + $attacker['user']['factor']['Attack']); //attaque
			$defTech	= (1 + $attacker['user']['factor']['Defensive']); //bouclier
			$shieldTech = (1 + $attacker['user']['factor']['Shield']); //coque
			$attackers[$fleetID]['techs'] = array($attTech, $shieldTech, $defTech);
			//------DK & SK
			$DK		= 1;
			$SK		= 1;
			
			if(empty($attacker['user']['damage_krit']))
			{$procen_DK = 0;}
			else
			{$procen_DK = $attacker['user']['damage_krit'] * $pricelist[1103]['cost'][902];}
			
			if(empty($attacker['user']['skil_deff_krit']))
			{$procen_SK = 0;}
			else
			{$procen_SK = $attacker['user']['skil_deff_krit'] * $pricelist[1303]['cost'][902];}
						
			if(rand(1,100) <= $procen_DK) $DK	= 2;
			if(rand(1,100) <= $procen_SK) $SK	= 2;		
			//---------------------------------------------------------------------
				
			foreach ($attacker['detail'] as $element => $amount) {
				if(in_array($element, $reslist['upgrade_fleet']))
				{	
					$thisAtt	= $amount * (($CombatCaps[$element]['attack']) * $attTech) * (1+$attacker['up']['a_'.$element]/100); //attaque
					$thisDef	= $amount * ((($pricelist[$element]['cost'][901] + $pricelist[$element]['cost'][902]) / 10) * (1+$attacker['up']['d_'.$element]/100)) *  $defTech ; //coque
					$thisShield	= $amount * (($CombatCaps[$element]['shield']) * $shieldTech) * (1+$attacker['up']['s_'.$element]/100) ; //bouclier
				}
				else
				{
					$thisAtt	= $amount * ($CombatCaps[$element]['attack']) * $attTech; //attaque
					$thisDef	= $amount * ($pricelist[$element]['cost'][901] + $pricelist[$element]['cost'][902]) / 10 * $defTech; //coque
					$thisShield	= $amount * ($CombatCaps[$element]['shield']) * $shieldTech ; //bouclier
				}
				$thisAtt 		*= $DK;
				$thisShield 	*= $SK;
				
				$attArray[$fleetID][$element] = array('def' => $thisDef, 'shield' => $thisShield, 'att' => $thisAtt);
				
				$attackDamage[$fleetID] += $thisAtt;
				$attackDamage['total'] += $thisAtt;
				$attackShield[$fleetID] += $thisDef;
				$attackShield['total'] += $thisDef;
				$attackAmount[$fleetID] += $amount;
				$attackAmount['total'] += $amount;
			}
			$temp1	= $attacker['detail'];
		}

		foreach ($defenders as $fleetID => $defender) {
			$defenseDamage[$fleetID] = 0;
			$defenseShield[$fleetID] = 0;
			$defenseAmount[$fleetID] = 0;
			//-----DEFENDER bonus
			if(empty($defender['user']['skil_deff_ob']))
			{$OB = 0;}
			else
			{$OB = ($defender['user']['skil_deff_ob'] * $pricelist[1306]['cost'][902]) / 100;}
			if(empty($defender['user']['skil_deff_os']))
			{$OS = 0;}
			else
			{$OS = ($defender['user']['skil_deff_os'] * $pricelist[1305]['cost'][902]) / 100;}
			//---------------------------------------------------------------------------------------------
			$attTech	= (1 + $defender['user']['factor']['Attack']); //attaquue
			$defTech	= (1 + $defender['user']['factor']['Defensive'] + $OB); //bouclier
			$shieldTech = (1 + $defender['user']['factor']['Shield'] + $OS); //coque
			$defenders[$fleetID]['techs'] = array($attTech, $shieldTech, $defTech);
			
			//------DK & SK
			$DK		= 1;
			$SK		= 1;
			
			if(empty($defender['user']['damage_krit']))
			{$procen_DK = 0;}
			else
			{$procen_DK = $defender['user']['damage_krit'] * $pricelist[1103]['cost'][902];}
			
			if(empty($defender['user']['skil_deff_krit']))
			{$procen_SK = 0;}
			else
			{$procen_SK = $defender['user']['skil_deff_krit'] * $pricelist[1303]['cost'][902];}
						
			if(rand(1,100) <= $procen_DK) $DK	= 2;
			if(rand(1,100) <= $procen_SK) $SK	= 2;		
			//---------------------------------------------------------------------
						
			foreach ($defender['def'] as $element => $amount) {
				if(in_array($element, $reslist['upgrade_fleet']))
				{	
					$thisAtt	= $amount * (($CombatCaps[$element]['attack']) * $attTech) * (1+$defender['up']['a_'.$element]/100); //attaque
					$thisDef	= $amount * ((($pricelist[$element]['cost'][901] + $pricelist[$element]['cost'][902]) / 10) * (1+$defender['up']['d_'.$element]/100)) *  $defTech ; //coque
					$thisShield	= $amount * (($CombatCaps[$element]['shield']) * $shieldTech) * (1+$defender['up']['s_'.$element]/100) ; //bouclier
				}
				else
				{
					$thisAtt	= $amount * ($CombatCaps[$element]['attack']) * $attTech; //attaque
					$thisDef	= $amount * ($pricelist[$element]['cost'][901] + $pricelist[$element]['cost'][902]) / 10 * $defTech ; //coque 
					$thisShield	= $amount * ($CombatCaps[$element]['shield']) * $shieldTech ; //bouclier
				}
				
				$thisAtt 		*= $DK;
				$thisShield 	*= $SK;
				
				if ($element == 407 || $element == 408 || $element == 409) $thisAtt = 0;

				$defArray[$fleetID][$element] = array('def' => $thisDef, 'shield' => $thisShield, 'att' => $thisAtt);			
			

				$defenseDamage[$fleetID] += $thisAtt;
				$defenseDamage['total'] += $thisAtt;
				$defenseShield[$fleetID] += $thisShield;
				$defenseShield['total'] += $thisShield;
				$defenseAmount[$fleetID] += $amount;
				$defenseAmount['total'] += $amount;
			}
			$temp2	= $defender['def'];
		}

		$ROUND[$ROUNDC] = array('attackers' => $attackers, 'defenders' => $defenders, 'attackA' => $attackAmount, 'defenseA' => $defenseAmount, 'infoA' => $attArray, 'infoD' => $defArray);

		if ($ROUNDC >= MAX_ATTACK_ROUNDS || $defenseAmount['total'] <= 0 || $attackAmount['total'] <= 0) {
			break;
		}

		// Calculate hit percentages (ACS only but ok)
		$attackPct = array();
		foreach ($attackAmount as $fleetID => $amount) {
			if (!is_numeric($fleetID)) continue;
				$attackPct[$fleetID] = $amount / $attackAmount['total'];
		}

		$defensePct = array();
		foreach ($defenseAmount as $fleetID => $amount) {
			if (!is_numeric($fleetID)) continue;
				$defensePct[$fleetID] = $amount / $defenseAmount['total'];
		}

		// CALCUL DES PERTES !!!
		$attacker_n = array();
		$attacker_shield = 0;
		$defenderAttack	= 0;
		foreach ($attackers as $fleetID => $attacker) {
			$attacker_n[$fleetID] = array();

			foreach($attacker['detail'] as $element => $amount) {
				if ($amount <= 0) {
					$attacker_n[$fleetID][$element] = 0;
					continue;
				}				

				$defender_moc = $amount * ($defenseDamage['total'] * $attackPct[$fleetID]) / $attackAmount[$fleetID];
				$defenseAmountRF = 0;
				if(isset($RF[$element])) {
					foreach($RF[$element] as $shooter => $shots) {
						foreach($defArray as $fID => $rfdef) {
							if(empty($rfdef[$shooter]['att']) || $attackAmount[$fleetID] <= 0) continue;					

							$defender_moc += $rfdef[$shooter]['att'] * $shots / ($amount / $attackAmount[$fleetID] * $attackPct[$fleetID]);
							$defenseAmountRF += $defenders[$fID]['def'][$shooter] * $shots;
						}
					}
				}
				
				$defenderAttack	+= $defender_moc;
				
				if (($attArray[$fleetID][$element]['shield'] / $amount) >= $defender_moc) {
					$attacker_n[$fleetID][$element] = round($amount);
					$attacker_shield += $defender_moc;
					continue;
				}			
								
				$max_removePoints = floor($amount * ($defenseAmount['total']+$defenseAmountRF) / $attackAmount[$fleetID] * $attackPct[$fleetID]);
				$attacker_shield += min($attArray[$fleetID][$element]['shield'], $defender_moc);
				$defender_moc 	 -= min($attArray[$fleetID][$element]['shield'], $defender_moc);	
							
				$ile_removePoints = max(min($max_removePoints, $amount * min($defender_moc / $attArray[$fleetID][$element]['def'], 1)), 0);
				
				$attacker_n[$fleetID][$element] = max(ceil($amount - $ile_removePoints), 0);
			}
		}

		$defender_n = array();
		$defender_shield = 0;
		$attackerAttack	= 0;
		foreach ($defenders as $fleetID => $defender) {
			$defender_n[$fleetID] = array();

			foreach($defender['def'] as $element => $amount) {
				if ($amount <= 0) {
					$defender_n[$fleetID][$element] = 0;
					continue;
				}
				
				$attacker_moc = $amount * ($attackDamage['total'] * $defensePct[$fleetID]) / $defenseAmount[$fleetID];
				$attackAmountRF = 0;
				if (isset($RF[$element])) {
					foreach($RF[$element] as $shooter => $shots) {
						foreach($attArray as $fID => $rfatt) {
							if (empty($rfatt[$shooter]['att']) || $defenseAmount[$fleetID] <= 0 ) continue;

							$attacker_moc += $rfatt[$shooter]['att'] * $shots / ($amount / $defenseAmount[$fleetID] * $defensePct[$fleetID]);
							$attackAmountRF += $attackers[$fID]['detail'][$shooter] * $shots;
						}
					}
				}
				
				$attackerAttack	+= $attacker_moc;
				
				if (($defArray[$fleetID][$element]['shield'] / $amount) >= $attacker_moc) {
					$defender_n[$fleetID][$element] = round($amount);
					$defender_shield += $attacker_moc;
					continue;
				}
					
				$max_removePoints = floor($amount * ($attackAmount['total']+$attackAmountRF) / $defenseAmount[$fleetID] * $defensePct[$fleetID]);			
				$defender_shield += min($defArray[$fleetID][$element]['shield'], $attacker_moc);
				$attacker_moc 	 -= min($defArray[$fleetID][$element]['shield'], $attacker_moc);				
		
				$ile_removePoints = max(min($max_removePoints, $amount * min($attacker_moc / $defArray[$fleetID][$element]['def'], 1)), 0);

				$defender_n[$fleetID][$element] = max(ceil($amount - $ile_removePoints), 0);
			}
		}
		
		$ROUND[$ROUNDC]['attack'] 		= $attackerAttack;
		$ROUND[$ROUNDC]['defense'] 		= $defenderAttack;
		$ROUND[$ROUNDC]['attackShield'] = $attacker_shield;
		$ROUND[$ROUNDC]['defShield'] 	= $defender_shield;
		foreach ($attackers as $fleetID => $attacker) {
			$attackers[$fleetID]['detail'] =  array_map('round', $attacker_n[$fleetID]);
		}

		foreach ($defenders as $fleetID => $defender) {
			$defenders[$fleetID]['def'] = array_map('round', $defender_n[$fleetID]);
		}
	}
	
	if ($attackAmount['total'] <= 0 && $defenseAmount['total'] > 0) {
		$won = "r"; // defender
	} elseif ($attackAmount['total'] > 0 && $defenseAmount['total'] <= 0) {
		$won = "a"; // attacker
	} else {
		$won = "w"; // draw
	}

	// CDR
	foreach ($attackers as $fleetID => $attacker) {					   // flotte attaquant en CDR
		foreach ($attacker['detail'] as $element => $amount) {
			$TRES['attacker'] -= $pricelist[$element]['cost'][901] * $amount ;
			$TRES['attacker'] -= $pricelist[$element]['cost'][902] * $amount ;

			$ARES['metal'] -= $pricelist[$element]['cost'][901] * $amount ;
			$ARES['crystal'] -= $pricelist[$element]['cost'][902] * $amount ;
		}
	}

	$DRESDefs = array('metal' => 0, 'crystal' => 0);
	
	//------Reductin defender
	$RD		= 0;			
	if(empty($defender['user']['skil_vost_deff']))
	{$RD 	= 0;}
	else
	{$RD 	= $defender['user']['skil_vost_deff'];}	
	//---------------------------------------------------------------------

	foreach ($defenders as $fleetID => $defender) {
		foreach ($defender['def'] as $element => $amount) {
			if ($element < 300) {							// flotte defenseur en CDR
				$DRES['metal'] 	 -= $pricelist[$element]['cost'][901] * $amount ;
				$DRES['crystal'] -= $pricelist[$element]['cost'][902] * $amount ;

				$TRES['defender'] -= $pricelist[$element]['cost'][901] * $amount ;
				$TRES['defender'] -= $pricelist[$element]['cost'][902] * $amount ;
			} else {									// defs defenseur en CDR + reconstruction
				$TRES['defender'] -= $pricelist[$element]['cost'][901] * $amount ;
				$TRES['defender'] -= $pricelist[$element]['cost'][902] * $amount ;

				$lost = $STARTDEF[$element] - $amount;
				$giveback = round($lost * (rand(56+$RD, 70+$RD) / 100));
				$defenders[$fleetID]['def'][$element] += $giveback;
				$DRESDefs['metal'] 	 += $pricelist[$element]['cost'][901] * ($lost - $giveback) ;
				$DRESDefs['crystal'] += $pricelist[$element]['cost'][902] * ($lost - $giveback) ;
			}
		}
	}
	
	$ARES['metal']		= max($ARES['metal'], 0);
	$ARES['crystal']	= max($ARES['crystal'], 0);
	$DRES['metal']		= max($DRES['metal'], 0);
	$DRES['crystal']	= max($DRES['crystal'], 0);
	$TRES['attacker']	= max($TRES['attacker'], 0);
	$TRES['defender']	= max($TRES['defender'], 0);
	
	$totalLost = array('att' => $TRES['attacker'], 'def' => $TRES['defender']);
	$debAttMet = ($ARES['metal'] * ($FleetTF / 100));
	$debAttCry = ($ARES['crystal'] * ($FleetTF / 100));
	$debDefMet = ($DRES['metal'] * ($FleetTF / 100)) + ($DRESDefs['metal'] * ($DefTF / 100));
	$debDefCry = ($DRES['crystal'] * ($FleetTF / 100)) + ($DRESDefs['crystal'] * ($DefTF / 100));

	return array('won' => $won, 'debree' => array('att' => array($debAttMet, $debAttCry), 'def' => array($debDefMet, $debDefCry)), 'rw' => $ROUND, 'lost' => $totalLost);
}
?>